package com.example.lp.contentprovider;

import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.lp.R;

public class ProviderActivity extends AppCompatActivity implements View.OnClickListener {

    private static String TAG = "ProviderActivity";
    private TextView showText;
    private Button btn_update, btn_insert, btn_delete, btn_query;
    private Uri uri = Uri.parse("content://com.lp.test.myprovider");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "onCreate: ");
        setContentView(R.layout.activity_provider);
        initViews();
    }

    private void initViews() {
        Log.i(TAG, "initViews: ");
        showText = findViewById(R.id.tv_result);
        btn_update = findViewById(R.id.btn_update);
        btn_insert = findViewById(R.id.btn_insert);
        btn_delete = findViewById(R.id.btn_delete);
        btn_query = findViewById(R.id.btn_query);
        btn_update.setOnClickListener(this);
        btn_query.setOnClickListener(this);
        btn_insert.setOnClickListener(this);

    }

    private int conut=2;
    @Override
    public void onClick(View v) {
        Log.i(TAG, "onClick: ");

        if (v.getId() == R.id.btn_update) {
            Log.i(TAG, "update: ");
        } else if (v.getId() == R.id.btn_insert) {
            Log.i(TAG, "onClick: ");
            ContentValues contentValues = new ContentValues();
            contentValues.put("_id",conut++);
            contentValues.put("name", "book"+conut);
            getContentResolver().insert(MyContentProvider.BOOK_URI, contentValues);
            showText.setText("insert :"+contentValues.toString());
        } else if (v.getId() == R.id.btn_delete) {

        } else if (v.getId() == R.id.btn_query) {
            Log.i(TAG, "onClick: ");
            Cursor cursor = getContentResolver().query(MyContentProvider.BOOK_URI, null, null, null, null, null);
            if (cursor != null && cursor.getCount() > 0) {
                StringBuilder result=new StringBuilder();
                while (cursor.moveToNext()) {
                    String name = cursor.getString(cursor.getColumnIndex("name"));
                    int id = cursor.getInt(cursor.getColumnIndex("_id"));
                    String str="book:" + "name = " + name + ",id = " + id;
                    Log.i(getClass().getSimpleName(), str);
                    result.append(str);
                }
                cursor.close();
                showText.setText(result.toString());
            }

        }
    }

    private void doProvider() {

    }
}
